package jwdt.xadmin.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import jwdt.common.bean.Tree;
import jwdt.common.dao.BaseDao;
import jwdt.xadmin.system.bean.QXCD;
import jwdt.xadmin.system.service.CdManageService;

import com.ezerg.db.Jdb;
import com.ezerg.db.ext.PageUtil;

public class CdManageServiceImpl implements CdManageService {
	
	private BaseDao<QXCD> baseDao;

	public void setBaseDao(BaseDao<QXCD> baseDao) {
		this.baseDao = baseDao;
	}
	
	@Override
	public PageUtil selectCdList(PageUtil pu, String sjcd) throws Exception {
		String where = " sjcd='" + sjcd + "' and zt=1 order by px";
		pu.doList(QXCD.class, where);
		return pu;
	}
	
	@Override
	public QXCD selectOneCd(String cddm) throws Exception {
		return (QXCD)Jdb.get().get(QXCD.class, cddm);
	}
	
	@Override
	public String addCd(QXCD obj) throws Exception {
		return baseDao.doAddObj(obj);
	}
	
	@Override
	public String saveCd(String cddm,QXCD obj) throws Exception {
		return baseDao.doUpdateObj(QXCD.class, cddm, obj);
	}
	
	@Override
	public String delCd(String cddm) throws Exception {
		return baseDao.doDelObj(QXCD.class, cddm);
	}
	
	@SuppressWarnings("unchecked")
	public List<Tree> cdLeftTree()throws Exception{
		List<QXCD> types = Jdb.get().query(QXCD.class,"sjcd='' and zt=1 ORDER BY px");
		List<Tree> list = new ArrayList<Tree>();
		Tree tree = new Tree();
		tree.setId("0");
		tree.setText("全部菜单");
		tree.setIconCls("icon-install");
		tree.setChildren(treeList(types,null));
		list.add(tree);
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<Tree> treeList(List<QXCD> cds,List<Integer> quanxian)throws Exception{
		List<Tree> treeList = new ArrayList<Tree>();
		for(QXCD cd:cds) {
			Tree tree = new Tree();
			if(quanxian==null || quanxian.contains(cd.getCddm())) {
				tree.setId(cd.getCddm());
				tree.setText(cd.getCdmc());
				if(cd.getZcd()!=null && cd.getZcd().size()>0){
					tree.setState(Tree.STATE_CLOSED);//非叶子节点，否则死循环
					tree.setChildren(treeList(cd.getZcd(),quanxian));
				}
				treeList.add(tree);
			}
		}
		return treeList;
	}
}
